package com.jingdianjichi.subject.domain.service.Imp;

import com.jingdianjichi.subject.common.entity.PageResult;
import com.jingdianjichi.subject.common.enums.IsDeleteFlagEnum;
import com.jingdianjichi.subject.domain.convert.SubjectInfoConvert;
import com.jingdianjichi.subject.domain.convert.SubjectLabelConvert;
import com.jingdianjichi.subject.domain.entity.SubjectInfoBO;
import com.jingdianjichi.subject.domain.entity.SubjectOptionBo;
import com.jingdianjichi.subject.domain.handler.Subject.SubjectTypeHandler;
import com.jingdianjichi.subject.domain.handler.Subject.SubjectTypeHandlerFactory;
import com.jingdianjichi.subject.domain.service.SubjectDomainService;
import com.jingdianjichi.subject.infra.basic.entity.SubjectInfo;
import com.jingdianjichi.subject.infra.basic.entity.SubjectLabel;
import com.jingdianjichi.subject.infra.basic.entity.SubjectMapping;
import com.jingdianjichi.subject.infra.basic.mapper.SubjectInfoDao;
import com.jingdianjichi.subject.infra.basic.service.SubjectInfoService;
import com.jingdianjichi.subject.infra.basic.service.SubjectLabelService;
import com.jingdianjichi.subject.infra.basic.service.SubjectMappingService;
import com.jingdianjichi.subject.infra.basic.service.impl.SubjectLabelServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SubjectInfoServiceDomainImp implements SubjectDomainService {
    @Resource
    private  SubjectInfoService subjectInfoService;
    @Resource  //工厂注入
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;
    @Resource
    private SubjectMappingService   subjectMappingService;
    private SubjectInfoDao subjectInfoDao;
    @Autowired
    private SubjectLabelServiceImpl subjectLabelService;


    @Transactional(rollbackFor = Exception.class) //涉及多表查询
    @Override
    public void add(SubjectInfoBO subjectInfoBO) {
        if (log.isInfoEnabled()){
            log.info("SubjectInfoServiceDomainImp add subjectInfoBO:{}", subjectInfoBO);
        }
        //因为有多种题型增加会产生大量的if 所以为了避免代码繁琐 采用工厂加策略的形式
        //一个工厂包含四种类型，根据传入type类型自动映射处理
        SubjectInfo subjectInfo = SubjectInfoConvert.INSTANCE.convertBoToSubject(subjectInfoBO);
        subjectInfo.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo);
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        subjectInfoBO.setId(subjectInfo.getId());
        handler.add(subjectInfoBO);
        List<Integer> categoryIds = subjectInfoBO.getCategoryIds();
        List<Integer> labelIds = subjectInfoBO.getLabelIds();
        List<SubjectMapping> mappings=new LinkedList<>();
        //组装mapping  mapping之中是多对多的关系 mapping id->多个题目id->多个种类id->多个标签id
        //
        // 一个题目id 匹配 多个种类 一个种类又匹配多个标签
        for (Integer categoryId : categoryIds) {
            labelIds.forEach(labelId -> {
                SubjectMapping subjectMapping = new SubjectMapping();
                subjectMapping.setSubjectId(subjectInfo.getId());
                subjectMapping.setCategoryId(Long.valueOf(categoryId));
                subjectMapping.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
                subjectMapping.setLabelId(Long.valueOf(labelId));
                mappings.add(subjectMapping);
            });
        }

        subjectMappingService.batchInsert(mappings);

    }

    /**
     * 查询题目列表
     * @param subjectInfoBO
     * @return
     */
    @Override
    public PageResult<SubjectInfoBO> getSubjectPage(SubjectInfoBO subjectInfoBO) {
        PageResult<SubjectInfoBO> pageResult = new PageResult<>();
        pageResult.setPageSize(subjectInfoBO.getPageSize());
        pageResult.setPageNo(subjectInfoBO.getPageNo());
        int start=(subjectInfoBO.getPageNo()-1)*subjectInfoBO.getPageSize();
        SubjectInfo subjectInfo=SubjectInfoConvert.INSTANCE.convertBoToSubject(subjectInfoBO);
        //查询 符合条件的 题目总数
        int count =subjectInfoService.countByCondition(subjectInfo,subjectInfoBO.getCategoryId(),subjectInfoBO.getLabelId());
        if (count==0){
            return pageResult;
        }
        List<SubjectInfo> subjectInfoList= subjectInfoService.queryPage(subjectInfo,subjectInfoBO.getCategoryId()
                ,subjectInfoBO.getLabelId(),start,subjectInfoBO.getPageSize());
        List<SubjectInfoBO> subjectInfos = SubjectInfoConvert.INSTANCE.convertListBoToSubject(subjectInfoList);
        pageResult.setReCords(subjectInfos);
        pageResult.setTotal(count);
        return pageResult;

    }

    @Override
    public SubjectInfoBO querySubjectInfo(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo=subjectInfoService.queryById(subjectInfoBO.getId());
        if (subjectInfo == null) {
            log.error("未找到对应的题目信息，ID: {}", subjectInfoBO.getId());
            throw new RuntimeException("未找到对应的题目信息");
        }
        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        SubjectOptionBo optionBo = handler.query(subjectInfo.getId());
        SubjectInfoBO bo = SubjectInfoConvert.INSTANCE.convertOptionBoToSubject(optionBo, subjectInfo);
        //获取标签名字
        SubjectMapping subjectMapping=new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeleteFlagEnum.UN_DELETED.getCode());
        List<SubjectMapping> labelMappings=subjectLabelService.queryLabelId(subjectMapping);
        if(labelMappings.isEmpty()){
            return bo;
        }
        List<Long> labelIdList = labelMappings.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> subjectLabels=subjectLabelService.batchQueryById(labelIdList);
        List<String> labelNames=subjectLabels.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
        bo.setLabelName(labelNames);
        return bo;
    }
}
